import React, { useState } from 'react';
import { Table, Space, Popconfirm, Button } from 'antd';
import { connect } from 'umi';
import UserModal from './components/UserModal'

const index = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [record, setRecord] = useState(undefined)

  // 弹出对话框显示事件
  const showModal = (record) => {
    setIsModalVisible(true)
    setRecord(record)
  }

  // 弹出对话框取消事件
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 弹出气泡框确认事件
  function confirm(record) {
    // message.success('Click on Yes');
    const id = record.id
    props.dispatch({
      type: 'users/delete',
      payload: {
        id
      }
    })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Create Time',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => { showModal(record) }}>edit</a>
          <Popconfirm
            title="Are you sure to delete this record?"
            onConfirm={() => { confirm(record) }}
            okText="Yes"
            cancelText="No"
          >
            <a href="#">Delete</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 弹出对话框确认完成事件
  const onFinish = values => {
    // console.log('Success:', values);
    let id = 0;
    if (record) {
      id = record.id
    }
    if (id) {
      props.dispatch({
        type: 'users/edit',
        payload: {
          id,
          values
        }
      })
    } else {
      props.dispatch({
        type: 'users/add',
        payload: {
          values
        }
      })
    }
    setIsModalVisible(false);
  };

  // 添加事件
  const addHandler = () => {
    setIsModalVisible(true);
    setRecord(undefined)
  }

  return (
    <div className="list-table">
      <Button type="primary" onClick={addHandler}>Add</Button>
      <Table columns={columns} dataSource={props.data} rowKey='id' loading={props.userListLoading} />
      <UserModal visible={isModalVisible} cancel={handleCancel} record={record} onFinish={onFinish} />
    </div>
  );
};

const mapStateToProps = (state) => {
  // console.log(state)
  // console.log(state.loading)
  return { data: state.users.data, userListLoading: state.loading.models.users };
};

export default connect(mapStateToProps)(index);
